package com.whstudio.multithreading;
public class KeepKeeperAlive {
	public KeepKeeperAlive(){
		Keeper keeper=new Keeper();
		keeper.start();
	}
	
	class Keeper extends Thread{
		String time=new String(Messages.getString("time")); //$NON-NLS-1$;
		public void run(){
			while(true){
				keepTomcatAlive();
				try {
					if(time==null||time.equals("")){
						time="5000";
					}
					System.out.println(time);
					sleep(Integer.parseInt(time));
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
		
		public void keepTomcatAlive(){
			String s;
			String t = new String(Messages.getString("KeepKeeperAlive.0")); //$NON-NLS-1$
			int javaCount = 0;
			try {
				java.lang.Process p = java.lang.Runtime.getRuntime().exec(
						Messages.getString("KeepKeeperAlive.1")); //$NON-NLS-1$
				java.io.BufferedReader in = new java.io.BufferedReader(
						new java.io.InputStreamReader(p.getInputStream()));
				while ((s = in.readLine()) != null) {
					if (s.startsWith(t)){
						javaCount++;
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			System.out.println(Messages.getString("KeepKeeperAlive.2")+(javaCount==2?Messages.getString("KeepKeeperAlive.3"):Messages.getString("KeepKeeperAlive.4"))); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
			if (javaCount<2){
				restartTomcat();
			}
		}
		
		public void restartTomcat() {
			try {
				java.lang.Runtime.getRuntime().exec(Messages.getString("KeepKeeperAlive.5")+Messages.getString("KeepKeeperAlive.6")); //$NON-NLS-1$ //$NON-NLS-2$
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	public static void main(String[] args) {
		new KeepKeeperAlive();
	}
}
